<template>
  <div class="upload-container">
    <el-button
      icon="el-icon-upload"
      size="mini"
      :style="{ background: color, borderColor: color }"
      @click="dialogVisible = true"
      type="primary"
      >上传图片
    </el-button>
    <el-dialog append-to-body v-model="dialogVisible">
      <el-upload
        class="editor-slide-upload"
        :action="useOss ? ossUploadUrl : minioUploadUrl"
        :data="useOss ? dataObj : null"
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        list-type="picture-card"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { policy } from '@/api/oss'
import { ElMessage } from 'element-plus'
defineOptions({
  name: 'EditorSlideUpload',
})
const props = defineProps({
  color: {
    type: String,
    default: '#1890ff',
  },
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '100%',
  },
})
const emit = defineEmits(['successCBK'])
const filedialogVisibleist = ref(false)
const dialogVisible = ref(false)
const listObj = ref({})
const fileList = ref([])
const dataObj = ref({
  policy: '',
  signature: '',
  key: '',
  ossaccessKeyId: '',
  dir: '',
  host: '',
})
const useOss = ref(false) //使用oss->true;使用MinIO->false
const ossUploadUrl = 'http://macro-oss.oss-cn-shenzhen.aliyuncs.com'
const minioUploadUrl = 'http://localhost:8080/minio/upload'

function checkAllSuccess() {
  return Object.keys(listObj.value).every((item) => listObj.value[item].hasSuccess)
}
function handleSubmit() {
  const arr = Object.keys(listObj.value).map((v) => listObj.value[v])
  if (!checkAllSuccess()) {
    ElMessage.success('请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！')
    return
  }
  console.log(arr)
  emit('successCBK', arr)
  listObj.value = {}
  fileList.value = []
  filedialogVisibleist.value = false
}
function handleSuccess(response, file) {
  const uid = file.uid
  const objKeyArr = Object.keys(listObj.value)
  for (let i = 0, len = objKeyArr.length; i < len; i++) {
    if (listObj.value[objKeyArr[i]].uid === uid) {
      listObj.value[objKeyArr[i]].url = dataObj.value.host + '/' + dataObj.value.dir + '/' + file.name
      if (!useOss.value) {
        //不使用oss直接获取图片路径
        listObj.value[objKeyArr[i]].url = response.data.url
      }
      listObj.value[objKeyArr[i]].hasSuccess = true
      return
    }
  }
}
function handleRemove(file) {
  const uid = file.uid
  const objKeyArr = Object.keys(listObj.value)
  for (let i = 0, len = objKeyArr.length; i < len; i++) {
    if (listObj.value[objKeyArr[i]].uid === uid) {
      delete listObj.value[objKeyArr[i]]
      return
    }
  }
}
function beforeUpload(file) {
  const fileName = file.uid
  listObj.value[fileName] = {}
  if (!useOss.value) {
    //不使用oss不需要获取策略
    listObj.value[fileName] = {
      hasSuccess: false,
      uid: file.uid,
      width: props.width,
      height: props.height,
    }
    return true
  }
  return new Promise((resolve, reject) => {
    policy()

        dataObj.value.policy = response.data.policy
        dataObj.value.signature = response.data.signature
        dataObj.value.ossaccessKeyId = response.data.accessKeyId
        dataObj.value.key = response.data.dir + '/${filename}'
        dataObj.value.dir = response.data.dir
        dataObj.value.host = response.data.host
        listObj.value[fileName] = {
          hasSuccess: false,
          uid: file.uid,
          width: props.width,
          height: props.height,
        }
        resolve(true)
      })
      .catch((err) => {
        console.log(err)
        reject(false)
      })
  })
}
</script>

<style lang="scss" scoped>
.upload-container .editor-slide-upload {
  margin-bottom: 20px;
}
</style>
